const Router = require("koa-router");
const moment = require('moment');
const userinfo = require('../mapper/User');
const prouter = new Router();
const nunjucks = require('nunjucks')
const views = require('koa-view');
const path = require('path');
prouter.use(views(path.join(__dirname,'../web'),{
    map:{
        html:'nunjucks'
    }
}))


//主页面
prouter.get('/',async(ctx,next)=>{
    let users = []
    await userinfo.findAll().then(e=>{
        e.forEach(ele=>{
            users.push(ele.dataValues);
        })
    })
    await ctx.render('test',{users:users}).then(e=>{
 
    });
})

//删除事件
prouter.get('/rm',async(ctx,next)=>{
    let id = ctx.query.id;
    console.log("删除事件"+id);
    await userinfo.destroy({
        where:{
            id:id
        }
    }).then(()=>{
            ctx.body = "删除成功"
        }
    ).catch(err=>{
        ctx.body = err+""
    })
})


//新增用户
prouter.post('/addUser',async(ctx,next)=>{
    console.log(ctx.request.body);
    let user = {
        account:ctx.request.body.account,
        password:ctx.request.body.password,
    }
    await userinfo.create(user).then(()=>{
        ctx.body = '添加成功'
    }).catch(()=>{
        ctx.body = '添加失败'
    })
})




module.exports = prouter;

